package com.gzsxy.exception;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gzsxy.cons.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author xiaolong
 * @version 1.0
 * @description: 访问拒绝处理器 -权限不足
 * @date 2021/11/8 9:57
 */
@Component("CustomAccessDeniedHandler")
public class CustomAccessDeniedHandler implements AccessDeniedHandler {

    @Autowired
    private ObjectMapper mapper;


    @Override
    public void handle(HttpServletRequest req, HttpServletResponse res, AccessDeniedException denyExcetion) throws IOException, ServletException {
        Map<Object, Object> map = new HashMap<>();
        map.put("code", HttpStatus.UNAUTHORIZED.getCode());
        map.put("msg","权限不足");
        map.put("data",denyExcetion.getMessage());
        map.put("success",false);
        map.put("path",req.getServletPath());
        map.put("timestamp",String.valueOf(System.currentTimeMillis()));
        res.setContentType("application/json;charset=UTF-8");
        res.setStatus(HttpStatus.UNAUTHORIZED.getCode());
        mapper.writeValue(res.getOutputStream(),map);

    }
}
